#pragma once

#include <algorithm>
#include "jsoncpp/json/json.h"
#include "index.hpp"
#include "log.hpp"

namespace ns_searcher
{
	using namespace ns_log;

	struct InvertedElemPrint
	{
		uint64_t doc_id;
		int weight;
		std::vector<std::string> words;
		InvertedElemPrint() : doc_id(0), weight(0) {}
	};

	class Searcher
	{
	private:
		ns_index::Index *index; // 供系统进行查找的索引
	public:
		Searcher() {}
		~Searcher() {}

	public:
		void InitSearcher(const std::string &input) // data/raw_html/raw.txt
		{
			// 1. 获取或者创建index对象
			index = ns_index::Index::GetInstance();
			LOG(INFO) << "获取index单例成功..." << std::endl;
			// 2. 根据index对象建⽴索引
			index->BuileIndex(input);
			LOG(INFO) << "建立正排和倒排索引成功..." << std::endl;
		}
		// query: 搜索关键字
		// json_string: 返回给⽤⼾浏览器的搜索结果
		void Search(const std::string &query, std::string *json_string)
		{
			// 1.[分词]:对我们的query进⾏按照searcher的要求进⾏分词
			std::vector<std::string> words;
			ns_util::JiebaUtil::CutString(query, &words);

			// 2.[触发]:就是根据分词的各个"词"，进⾏index查找
			std::vector<InvertedElemPrint> inverted_list_all;
			std::unordered_map<uint64_t, InvertedElemPrint> tokens_map;

			for (std::string word : words)
			{
				boost::to_lower(word);
				ns_index::InvertedList *inverted_list = index->GetInvertedList(word);
				if (inverted_list == nullptr)
				{
					continue;
				}
				for (const auto &elem : *inverted_list)
				{
					auto &item = tokens_map[elem.doc_id]; //[]:如果存在直接获取，如果不存在新建
					item.doc_id = elem.doc_id;
					item.weight += elem.weight;		//关键字对应越多权值越大
					item.words.push_back(elem.word);
				}
			}

			//去重
			for (const auto &item : tokens_map)
			{
				inverted_list_all.push_back(std::move(item.second));
			}

			// 3.[合并排序]：汇总查找结果，按照相关性(weight)降序排序
			std::sort(inverted_list_all.begin(), inverted_list_all.end(), [](const InvertedElemPrint &e1, const InvertedElemPrint &e2)
					  { return e1.weight > e2.weight; });

			// 4.[构建]:根据查找出来的结果，构建json串 -- jsoncpp
			Json::Value root;
			for (auto &it : inverted_list_all)
			{
				ns_index::DocInfo *doc = index->GetForwardIndex(it.doc_id);
				if (nullptr == doc)
				{
					continue;
				}
				Json::Value elem;
				elem["title"] = doc->title;
				elem["desc"] = GetDesc(doc->content, it.words[0]); // 只需要获取content一部分
				elem["url"] = doc->url;
				elem["id"] = (int)it.doc_id;
				elem["weight"]  = it.weight;

				root.append(elem);
			}

			// Json::FastWriter writer;
			Json::StyledWriter writer;
			*json_string = writer.write(root);
		}

	private:
		std::string GetDesc(const std::string &html_content, const std::string &word)
		{
			// 找到word在html_content中的首次出现，然后往前找50字节(如果没有，从begin开始)，往后找100字节(如果没有，到end就可以的)
			// 截取出这部分内容
			const int prev_step = 50;
			const int next_step = 100;
			// 1.找到首次出现
			auto iter = std::search(html_content.begin(), html_content.end(), word.begin(), word.end(), [](int x, int y)
									{ return (std::tolower(x) == std::tolower(y)); });
			if(iter == html_content.end())
			{
				return "None1";
			}
			int pos = std::distance(html_content.begin(),iter);
			
			//有bug，小写查找不到大写
			// size_t pos = html_content.find(word);
			// if(pos == std::string::npos)
			// {
			// 	return "None1";
			// }
			//2.获取start end
			int start = 0;
			int end = html_content.size() - 1;
			if(pos > start + prev_step) start = pos-prev_step;
			if(pos < (end - next_step)) end = pos + next_step;

			//3.获取字串
			if(start >= end) return "None2";
			std::string desc =  html_content.substr(start,end-start);
			desc += "...";
			return desc;
		}
	};
}